<template>
  <div class="patient-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2>患者管理</h2>
        <p>管理体检患者信息和档案</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreatePatient">
          <el-icon><Plus /></el-icon>
          新建患者
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入患者姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input
            v-model="searchForm.idCard"
            placeholder="请输入身份证号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="searchForm.gender"
            placeholder="请选择性别"
            clearable
            style="width: 120px"
          >
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 患者列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="patientList"
        stripe
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        
        <el-table-column prop="name" label="姓名" min-width="100" sortable="custom">
          <template #default="{ row }">
            <div class="patient-info">
              <el-avatar :size="32" :src="row.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="patient-name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === 'male' ? 'primary' : 'danger'" size="small">
              {{ row.gender === 'male' ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="age" label="年龄" width="80" sortable="custom" />
        
        <el-table-column prop="phone" label="手机号" min-width="120" />
        
        <el-table-column prop="idCard" label="身份证号" min-width="180" show-overflow-tooltip />
        
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        
        <el-table-column prop="emergencyContact" label="紧急联系人" min-width="120" />
        
        <el-table-column prop="emergencyPhone" label="紧急联系电话" min-width="140" />
        
        <el-table-column prop="lastCheckupDate" label="最后体检" width="120" sortable="custom">
          <template #default="{ row }">
            <span v-if="row.lastCheckupDate">
              {{ formatDate(row.lastCheckupDate) }}
            </span>
            <span v-else class="text-muted">未体检</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="160" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              text
              @click="handleViewPatient(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              text
              @click="handleEditPatient(row)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              text
              @click="handleCreateAppointment(row)"
            >
              预约
            </el-button>
            <el-button
              type="danger"
              size="small"
              text
              @click="handleDeletePatient(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 患者表单对话框 -->
    <PatientForm
      v-model:visible="formVisible"
      :patient="currentPatient"
      :is-edit="isEdit"
      @submit="handleFormSubmit"
    />

    <!-- 患者详情对话框 -->
    <PatientDetail
      v-model:visible="detailVisible"
      :patient="currentPatient"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PatientForm from '@/components/PatientForm.vue'
import PatientDetail from '@/components/PatientDetail.vue'

// 响应式数据
const loading = ref(false)
const patientList = ref([])

const searchForm = reactive({
  name: '',
  idCard: '',
  phone: '',
  gender: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const sortParams = reactive({
  sortBy: 'createdAt',
  sortOrder: 'desc'
})

const formVisible = ref(false)
const detailVisible = ref(false)
const currentPatient = ref(null)
const isEdit = ref(false)

// 模拟数据
const mockPatients = [
  {
    id: 1,
    name: '张三',
    gender: 'male',
    age: 35,
    phone: '13800138001',
    idCard: '110101198801011234',
    address: '北京市朝阳区某某街道123号',
    emergencyContact: '李四',
    emergencyPhone: '13800138002',
    lastCheckupDate: '2024-01-15',
    createdAt: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    name: '王五',
    gender: 'female',
    age: 28,
    phone: '13800138003',
    idCard: '110101199501011234',
    address: '北京市海淀区某某路456号',
    emergencyContact: '赵六',
    emergencyPhone: '13800138004',
    lastCheckupDate: null,
    createdAt: '2024-01-02 14:30:00'
  },
  {
    id: 3,
    name: '刘七',
    gender: 'male',
    age: 42,
    phone: '13800138005',
    idCard: '110101198201011234',
    address: '北京市西城区某某胡同789号',
    emergencyContact: '孙八',
    emergencyPhone: '13800138006',
    lastCheckupDate: '2024-01-10',
    createdAt: '2024-01-03 09:15:00'
  }
]

// 方法
const loadPatients = async () => {
  try {
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 这里应该调用实际的API
    // const result = await patientApi.getPatients(searchParams.value)
    
    // 模拟筛选和分页
    let filteredData = [...mockPatients]
    
    if (searchForm.name) {
      filteredData = filteredData.filter(p => p.name.includes(searchForm.name))
    }
    if (searchForm.idCard) {
      filteredData = filteredData.filter(p => p.idCard.includes(searchForm.idCard))
    }
    if (searchForm.phone) {
      filteredData = filteredData.filter(p => p.phone.includes(searchForm.phone))
    }
    if (searchForm.gender) {
      filteredData = filteredData.filter(p => p.gender === searchForm.gender)
    }
    
    pagination.total = filteredData.length
    
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    patientList.value = filteredData.slice(start, end)
    
  } catch (error) {
    ElMessage.error('获取患者列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadPatients()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    idCard: '',
    phone: '',
    gender: ''
  })
  pagination.page = 1
  loadPatients()
}

const handleSortChange = ({ prop, order }) => {
  if (order) {
    sortParams.sortBy = prop
    sortParams.sortOrder = order === 'ascending' ? 'asc' : 'desc'
  } else {
    sortParams.sortBy = 'createdAt'
    sortParams.sortOrder = 'desc'
  }
  loadPatients()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadPatients()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadPatients()
}

const handleCreatePatient = () => {
  currentPatient.value = null
  isEdit.value = false
  formVisible.value = true
}

const handleViewPatient = (patient) => {
  currentPatient.value = { ...patient }
  detailVisible.value = true
}

const handleEditPatient = (patient) => {
  currentPatient.value = { ...patient }
  isEdit.value = true
  formVisible.value = true
}

const handleCreateAppointment = (patient) => {
  // 跳转到预约页面并传递患者信息
  ElMessage.info(`为患者 ${patient.name} 创建预约功能待实现`)
}

const handleDeletePatient = async (patient) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除患者 "${patient.name}" 吗？此操作不可恢复。`,
      '删除患者',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用删除API
    // await patientApi.deletePatient(patient.id)
    
    ElMessage.success('患者删除成功')
    loadPatients()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('患者删除失败')
    }
  }
}

const handleFormSubmit = async (patientData) => {
  try {
    if (isEdit.value) {
      // await patientApi.updatePatient(currentPatient.value.id, patientData)
      ElMessage.success('患者信息更新成功')
    } else {
      // await patientApi.createPatient(patientData)
      ElMessage.success('患者创建成功')
    }
    formVisible.value = false
    loadPatients()
  } catch (error) {
    ElMessage.error(isEdit.value ? '患者信息更新失败' : '患者创建失败')
  }
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  loadPatients()
})
</script>

<style scoped>
.patient-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header-left h2 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.table-card :deep(.el-card__body) {
  padding: 0;
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.patient-name {
  font-weight: 500;
}

.text-muted {
  color: #bdc3c7;
  font-style: italic;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
  }
  
  .filter-card :deep(.el-form) {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-card :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 0;
  }
  
  .filter-card :deep(.el-input),
  .filter-card :deep(.el-select) {
    width: 100% !important;
  }
}

@media (max-width: 480px) {
  .pagination-wrapper {
    padding: 16px;
  }
  
  .pagination-wrapper :deep(.el-pagination) {
    justify-content: center;
  }
  
  .pagination-wrapper :deep(.el-pagination .el-pagination__sizes),
  .pagination-wrapper :deep(.el-pagination .el-pagination__jump) {
    display: none;
  }
}
</style>